package handlers

import (
	"edgex_back_management/defs"
	"edgex_back_management/session"
	"fmt"
	"log"
	"net/http"
)

var HeaderOfSession = "X-edgex-session-id"
var HeaderOfUserName = "X-degex-session-name"

func ValidateUserSession2(w http.ResponseWriter, r *http.Request) {
	if r.RequestURI == "/" || r.RequestURI == "/user/login" {
		return
	}
	fmt.Println("------ValidateUserSession--------")
	c, err := r.Cookie(HeaderOfSession)
	if err != nil {
		log.Printf("Error of validate User Session: can't get cookies: %v", err)
		defs.SendErrorResponse(w, defs.ErrorAuthExpired)
		//http.Redirect(w, r, "/user/login", 302)
		return
	}
	//sessionId := r.Header.Get(HeaderOfSession)
	//if len(sessionId) == 0 {
	//	return false
	//}

	sessionId := c.Value
	userName, expired := session.IsSessionExpired(sessionId)
	if expired {
		log.Printf("session expired, user:%s", userName)
		//http.Redirect(w, r, "/user/login", 302)
		defs.SendErrorResponse(w, defs.ErrorAuthExpired)
		return
	}

	r.Header.Add(HeaderOfUserName, userName)
	return
	//return true
}

func ValidateUserSession(r *http.Request) bool {
	if r.RequestURI == "/" || r.RequestURI == "/user/login" {
		//if r.RequestURI == "/" || r.RequestURI == "" {
		return true
	}
	fmt.Println("------ValidateUserSession--------")

	//sessionId := r.Header.Get(HeaderOfSession)
	sessionCookie, err := r.Cookie(HeaderOfSession)
	if sessionCookie == nil || err != nil {
		log.Printf("error of ValidateUserSession: %v \n", err)
		return false
	}

	sessionId := sessionCookie.Value

	if len(sessionId) == 0 {
		return false
	}

	userName, yes := session.IsSessionExpired(sessionId)
	if yes {
		return false
	}

	r.Header.Add(HeaderOfUserName, userName)
	return true
}

func ValidateAuthInfo(w http.ResponseWriter, r *http.Request) bool {
	c1, err := r.Cookie(HeaderOfSession)
	if err != nil {
		fmt.Fprintln(w, "Cannot get cookie")
	}
	fmt.Println("c1", c1)

	return true
}

func ValidateUser(w http.ResponseWriter, r *http.Request) bool {
	userName := r.Header.Get(HeaderOfUserName)
	if len(userName) == 0 {
		defs.SendErrorResponse(w, defs.ErrorNotAuthUser)
		return false
	}

	return true
}
